<template>
  <basic-container>
    <avue-crud
      :option="option"
      :search.sync="search"
      :table-loading="loading"
      :data="data"
      :page.sync="page"
      :permission="permissionList"
      :before-open="beforeOpen"
      v-model="form"
      ref="crud"
      @row-update="rowUpdate"
      @row-save="rowSave"
      @row-del="rowDel"
      @search-change="searchChange"
      @search-reset="searchReset"
      @selection-change="selectionChange"
      @current-change="currentChange"
      @size-change="sizeChange"
      @refresh-change="refreshChange"
      @sort-change="sortChange"
      @on-load="onLoad"
    >
      <template slot-scope="scope" slot="menu">
        <el-button
          icon="el-icon-view"
          size="small"
          type="text"
          v-if="permission.emp_policy_view"
          @click.stop="handleView(scope.row, scope.index)"
          >查 看</el-button
        >
        <el-button
          icon="el-icon-edit"
          size="small"
          type="text"
          v-if="permission.emp_policy_edit"
          @click.stop="handleEdit(scope.row, scope.index)"
          >编 辑</el-button
        >
      </template>
      <template slot="menuLeft">
        <el-button
          type="primary"
          icon="el-icon-plus"
          size="small"
          v-if="permission.emp_policy_add"
          @click.stop="handleSave"
          >新 增</el-button
        >
        <el-button
          type="danger"
          size="small"
          icon="el-icon-delete"
          plain
          v-if="permission.emp_policy_delete"
          @click="handleDelete"
          >删 除
        </el-button>
      </template>
      <template slot="menuRight">
        <el-button
          type="success"
          size="small"
          plain
          icon="el-icon-upload2"
          v-if="permission.emp_policy_import"
          @click="handleImport"
          >导入
        </el-button>
        <el-button
          type="warning"
          size="small"
          plain
          icon="el-icon-download"
          v-if="permission.emp_policy_export"
          @click="handleExport"
          >导出
        </el-button>
      </template>
    </avue-crud>
    <el-dialog
      :title="dialogText"
      top="1%"
      append-to-body
      :close-on-click-modal="false"
      :visible.sync="dialogVisible"
      :before-close="handleClose"
    >
      <div>
        <el-steps :active="active" simple>
          <el-step title="分配通道"></el-step>
          <el-step title="分润配置"></el-step>
        </el-steps>
      </div>
      <el-divider></el-divider>
      <template v-if="active == 0">
        <div class="haruyuki-ml-100 haruyuki-mb-20 haruyuki-flex haruyuki-flex-wrap" v-if="dialogType === 'add'">
          <div class="haruyuki-width-50 haruyuki-box-height-50">
            <span>选择员工：</span>
            <el-select
              size="small"
              value-key="code"
              v-model="employee"
              @change="userChange"
              placeholder="请选择员工"
            >
              <el-option
                v-for="item in userOptions"
                :key="item.code"
                :label="item.realName"
                :value="item"
              >
              </el-option>
            </el-select>
          </div>
        </div>
        <el-transfer
          class="haruyuki-width-100 haruyuki-flex-center"
          filterable
          :filter-method="filterMethod"
          filter-placeholder="请输入通道名称"
          :button-texts="['取消分配', '分配通道']"
          :titles="['未分配通道', '已分配通道']"
          v-model="aisleAllot"
          :data="aisleData"
        >
        </el-transfer>
      </template>
      <template v-if="active == 1">
        <policy-staff :oem="employee" identity-type="employee" :isTemplate="false" ref="toPolicyForm" />
      </template>
      <span slot="footer" class="dialog-footer">
        <el-button
          icon="el-icon-top"
          size="small"
          type="primary"
          v-preventClick
          @click="handlePageUp"
          v-if="active != 0"
          >上一页</el-button
        >
        <el-button icon="el-icon-bottom" size="small" @click="handlePageDown" v-preventClick
          >下一页</el-button
        >
      </span>
    </el-dialog>
    <el-dialog
      title="数据导入"
      append-to-body
      :visible.sync="excelBox"
      width="555px"
    >
      <avue-form
        :option="excelOption"
        v-model="excelForm"
        :upload-after="uploadAfter"
      >
        <template slot="excelTemplate">
          <el-button type="primary" @click="handleTemplate">
            点击下载<i class="el-icon-download el-icon--right"></i>
          </el-button>
        </template>
      </avue-form>
    </el-dialog>
  </basic-container>
</template>

<script>
import {
  getList,
  getDetail,
  add,
  update,
  remove,
} from "@/api/rb-service/emppolicy/emp_policy";
import { getAisleOemList } from "@/api/rb-service/serviceinfo/service_info";
import {
  add as addEmpAisle,
  update as updateEmpAisle,
  getList as getEmpAisleList,
} from "@/api/rb-service/emppolicy/emp_aisle";
import { getList as getUserList } from "@/api/system/user";
import { mapGetters } from "vuex";
import { getToken } from "@/util/auth";
import policyStaff from "@/components/rb-service/policy-staff";

export default {
  components: {
    policyStaff,
  },
  data() {
    return {
      form: {},
      query: {},
      search: {},
      loading: true,
      dialogVisible: false,
      dialogType: "", //打开类型 add/edit
      dialogText: "",
      active: 0,
      excelBox: false,
      page: {
        pageSize: 10,
        currentPage: 1,
        total: 0,
      },
      selectionList: [],
      option: {
        // height: "auto",
        calcHeight: 30,
        tip: false,
        border: true,
        index: true,
        viewBtn: false,
        addBtn: false,
        editBtn: false,
        selection: true,
        searchMenuSpan: 6,
        columnBtn: false,
        column: [
          {
            label: "id",
            prop: "id",
            type: "input",
            sortable: true,
            addDisplay: false,
            editDisplay: false,
            viewDisplay: false,
            hide: true,
          },
          {
            label: "用户编号",
            prop: "userNo",
            type: "input",
            sortable: true,
            search: true,
          },
          {
            label: "员工政策编号",
            prop: "empPolNo",
            type: "input",
            sortable: true,
            search: true,
          },
          {
            label: "员工名称",
            prop: "userName",
            type: "input",
            search: true,
          },
          {
            label: "政策名称",
            prop: "policyName",
            type: "input",
            search: true,
          },
          
        ],
      },
      data: [],
      employee: {},
      userOptions: [],
      aisleAllot: [], //通道分配 绑定value
      aisleData: [], //通道分配 数据
      excelForm: {},
      excelOption: {
        submitBtn: false,
        emptyBtn: false,
        column: [
          {
            label: "模板上传",
            prop: "excelFile",
            type: "upload",
            drag: true,
            loadText: "模板上传中，请稍等",
            span: 24,
            propsHttp: {
              res: "data",
            },
            tip: "请上传 .xls,.xlsx 标准格式文件",
            action: "/api/rb-service/service/emppolicy/emp_policy/import",
          },
          {
            label: "模板下载",
            prop: "excelTemplate",
            formslot: true,
            span: 24,
          },
        ],
      },
    };
  },
  computed: {
    ...mapGetters(["permission"]),
    permissionList() {
      return {
        addBtn: this.vaildData(this.permission.emp_policy_add, false),
        viewBtn: this.vaildData(this.permission.emp_policy_view, false),
        delBtn: this.vaildData(this.permission.emp_policy_delete, false),
        editBtn: this.vaildData(this.permission.emp_policy_edit, false),
      };
    },
    ids() {
      let ids = [];
      this.selectionList.forEach((ele) => {
        ids.push(ele.id);
      });
      return ids.join(",");
    },
  },
  methods: {
    /**
     * @func 上一页
     * @desc 员工费率表单 上一页
     * */
    handlePageUp() {
      if (this.active-- <= 0) this.active = 0;
    },
    /**
     * @func 下一页
     * @desc 员工费率表单 下一页
     * */
    handlePageDown() {
      const _this = this;
      switch (_this.active) {
        case 0:
          _this.aisleSubmit(_this.dialogType);
          break;
        case 1:
          _this.policySubmit(_this.dialogType);
          break;
      }
    },
    /**
     * @func 新增
     * @desc 点击新增初始化显示基本信息
     * */
    handleSave() {
      this.active = 0;
      this.dialogType = "add";
      this.dialogText = "新增";
      this.dialogVisible = true;
      getUserList("-1", "-1").then((res) => {
        this.userOptions = res.data.data.records;
      });
    },
    /**
     * @func 编辑
     * @desc 点击编辑回显基本信息
     * @param {Object} row - OEM表格绑定的信息
     * */
    handleEdit(row) {
      this.active = 0;
      this.dialogType = "edit";
      this.dialogText = "编辑";
      this.dialogVisible = true;
      this.employee.code = row.userNo;
      this.getAisle(this.dialogType);
    },
    /**
     * @func 关闭弹窗
     * @desc 点击关闭的回调
     * @param {Function} done - 完成的回调
     * */
    handleClose(done) {
      this.emptyForm();
      this.onLoad(this.page);
      done();
    },
    /* 服务商表单信息 清空 */
    emptyForm() {
      this.employee = {};
      this.aisleData = [];
      this.aisleAllot = [];
    },
    userChange() {
      this.getAisle();
    },
    /**
     * @func 获取员工通道信息
     * @desc 获取员工通道信息
     * */
    getAisle() {
      getAisleOemList("-1", "-1").then((res) => {
        let aisleData = res.data.data.records;
        aisleData.forEach((item, index) => {
          this.aisleData.push({
            label: item.aisleName,
            key: item.aisleCode,
            pinyin: item.aisleName[index],
          });
        });
      });
      getEmpAisleList("-1", "-1", {userNo: this.employee.code}).then((res) => {
        let aisleAllots = res.data.data.records;
        aisleAllots.forEach((item) => {
          this.aisleAllot.push(item.aisleCode);
        });
      });
    },
    /**
     * @func 员工通道提交
     * @desc 根据可选通道分配通道提交
     * @param {String} type - 类型(新增/修改)
     * */
    aisleSubmit(type) {
      if (!this.employee.code) return this.$message({ type: "warning", message: "请选择员工" });
      if (this.aisleAllot.length > 0) {
        if (type === "add") {
          let aisleDatas = {
            aisleCodes: this.aisleAllot,
            userNo: this.employee.code,
          };
          addEmpAisle(aisleDatas).then(
            (res) => {
              if (res.data.code == "200") {
                if (this.active++ > 4) this.active = 0;
              } else {
                this.$message({
                  type: "error",
                  message: res.data.message,
                });
              }
            },
            (error) => {
              window.console.log(error);
            }
          );
        } else if (type === "edit") {
          let aisleDatas = {
            aisleCodes: this.aisleAllot,
            userNo: this.employee.code,
          };
          updateEmpAisle(aisleDatas).then(
            (res) => {
              if (res.data.code == "200") {
                if (this.active++ > 4) this.active = 0;
              } else {
                this.$message({
                  type: "error",
                  message: res.data.message,
                });
              }
            },
            (error) => {
              window.console.log(error);
            }
          );
        } else {
          return false;
        }
      } else {
        this.$message({
          type: "warning",
          message: "请先选择通道!",
        });
      }
    },
    /**
     * @func 员工政策分润提交
     * @desc 根据已分配通道处理政策阶梯分润提交
     * @param {String} type - 类型(新增/修改)
     * */
    policySubmit(type) {
      if (type === "add") {
        let policyDatas = {
          "aisleList": this.$refs["toPolicyForm"].data,
          userNo: this.employee.code,
        };
        add(policyDatas).then(
          (res) => {
            if (res.data.code == "200") {
              this.$message({
                type: "success",
                message: "员工费率信息提交成功!",
              });
              this.dialogVisible = false;
              this.emptyForm();
              this.onLoad(this.page);
            } else {
              this.$message({
                type: "error",
                message: res.data.message,
              });
            }
          },
          (error) => {
            window.console.log(error);
          }
        );
      } else if (type === "edit") {
        let policyDatas = {
          "aisleList": this.$refs["toPolicyForm"].data,
          userNo: this.employee.code,
        };
        update(policyDatas).then(
          (res) => {
            if (res.data.code == "200") {
              this.$message({
                type: "success",
                message: "员工费率信息修改成功!",
              });
              this.dialogVisible = false;
              this.emptyForm();
              this.onLoad(this.page);
            } else {
              this.$message({
                type: "error",
                message: res.data.message,
              });
            }
          },
          (error) => {
            window.console.log(error);
          }
        );
      }
    },
    rowSave(row, done, loading) {
      add(row).then(
        () => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!",
          });
          done();
        },
        (error) => {
          loading();
          window.console.log(error);
        }
      );
    },
    rowUpdate(row, index, done, loading) {
      update(row).then(
        () => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!",
          });
          done();
        },
        (error) => {
          loading();
          window.console.log(error);
        }
      );
    },
    rowDel(row) {
      this.$confirm("确定将选择数据删除?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          return remove(row.id);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!",
          });
        });
    },
    handleDelete() {
      if (this.selectionList.length === 0) {
        this.$message.warning("请选择至少一条数据");
        return;
      }
      this.$confirm("确定将选择数据删除?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          return remove(this.ids);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!",
          });
          this.$refs.crud.toggleSelection();
        });
    },
    beforeOpen(done, type) {
      if (["edit", "view"].includes(type)) {
        getDetail(this.form.id).then((res) => {
          this.form = res.data.data;
        });
      }
      done();
    },
    searchReset() {
      this.query = {};
      this.onLoad(this.page);
    },
    searchChange(params, done) {
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },
    selectionChange(list) {
      this.selectionList = list;
    },
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    refreshChange() {
      this.onLoad(this.page, this.query);
    },
    onLoad(page, params = {}) {
      this.loading = true;
      getList(
        page.currentPage,
        page.pageSize,
        Object.assign(params, this.query)
      ).then((res) => {
        const data = res.data.data;
        this.page.total = data.total;
        this.data = data.records;
        this.loading = false;
        this.selectionClear();
      });
    },
    handleImport() {
      this.excelBox = true;
    },
    handleExport() {
      let exQuery = ``;
      exQuery += `&empPolNo=${this.search.empPolNo}`;
      exQuery += `&policyName=${this.search.policyName}`;
      exQuery += `&userNo=${this.search.userNo}`;
      this.$confirm("是否导出用户数据?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        window.open(
          `/api/rb-service/service/emppolicy/emp_policy/export?${
            this.website.tokenHeader
          }=${getToken()}` + exQuery
        );
      });
    },
    handleTemplate() {
      window.open(
        `/api/rb-service/service/emppolicy/emp_policy/export-template?${
          this.website.tokenHeader
        }=${getToken()}`
      );
    },
    uploadAfter(res, done) {
      this.excelBox = false;
      this.refreshChange();
      done();
    },
    sortChange(val) {
      if (val.order == "ascending") {
        //正序
        this.query.ascs = val.prop;
        this.query.descs = "";
      } else {
        //倒序
        this.query.descs = val.prop;
        this.query.ascs = "";
      }
      this.refreshChange();
    },
  },
};
</script>

<style lang="scss" scoped>
/deep/.el-transfer-panel__list.is-filterable {
  width: 400px !important;
  height: 500px !important;
}

/deep/.el-transfer-panel {
  width: 400px !important;
  height: 500px !important;
}
</style>
